<?php

namespace app\backend\controller;

use surface\helper\Builder;
use app\backend\controller\attachment\Search;
use app\backend\controller\attachment\Table;
use app\backend\logic\Attachment as AttachmentLogic;
use app\backend\logic\Uploader;
use think\facade\View;

/**
 *
 * @Group("attachment")
 * Class Attachment
 *
 * Author: zsw iszsw@qq.com
 */
class Attachment extends BackendController
{

    /**
     * @Route("index", method="*")
     */
    public function index()
    {
        return $this->createTable(new Table());
    }

    /**
     * @Route("delete", method="DELETE")
     */
    public function delete($id)
    {
        if(AttachmentLogic::delete($id)){
            return _success("删除成功");
        }
        return _error("删除失败");
    }

    private function builderSearch()
    {
        $search = Builder::form(new Search());
        $search->execute();
        $search->search(true);
        $search->options([
                             'props' => [
                                 'inline' => true,
                             ],
                             'submitBtn' => [
                                 'props' => [
                                     'prop' => [
                                         'icon' => 'el-icon-search',
                                     ],
                                 ]
                             ]
                         ]);

        return $search;
    }

    /**
     * @Route("manage", method="GET")
     */
    public function manage()
    {
        $search = $this->builderSearch();
        $searchOptions = $search->getGlobals()->format();

        return View::fetch('', [
            'search' => [
                'theme' => implode('', $search->theme()),
                'style' => implode('', $search->getStyle()),
                'script' => implode('', $search->getScript()),
                'options' => json_encode(count($searchOptions) > 0 ? $searchOptions : (object)[], JSON_UNESCAPED_UNICODE),
                'columns' => json_encode($search->getColumns(), JSON_UNESCAPED_UNICODE),
            ],
            'ext'    => (new Uploader())->getExt(),
        ]);
    }

    /**
     * 文件上传
     *
     * 文件 | base64
     *
     * @Route("upload", method="POST")
     */
    public function upload(){
        try {
            if (input('base64')) {
                $file = input('img_base64_data');
            }else{
                $file = request()->file('file');
            }
            $fileType = input('fileType', 'image');
            $url = (new Uploader)->handle($file, [
                'uploader' => session('admin.id'),
            ], $fileType);
        } catch (\Exception $e){
            return _error($e->getMessage());
        }
        return _success("上传成功", ['url' => $url]);
    }

}
